import { createStore } from "vuex";
import { Router } from "vue-router";

export default createStore({
  state: {
    token: null,
    equipTypes: [], // 装备类型数据
    equipTypesLoaded: false, // 是否已加载装备类型数据
  },
  getters: {
    isAuthenticated: (state) => !!state.token,
    token: (state) => state.token,
    equipTypes: (state) => state.equipTypes,
    equipTypesLoaded: (state) => state.equipTypesLoaded,
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      localStorage.setItem("token", token);
    },
    clearToken(state) {
      state.token = null;
      localStorage.removeItem("token");
    },
    setEquipTypes(state, types) {
      state.equipTypes = types;
      state.equipTypesLoaded = true;
    },
  },
  actions: {
    /**
     * 初始化token
     * @param param0
     */
    initializeToken({ commit }) {
      const token = localStorage.getItem("token");
      if (token) {
        commit("setToken", token);
      }
    },
    navigate({ }, { router, routeName }: { router: Router; routeName: string }) {
      router.push(routeName);
    },
    /**
     * 加载装备类型数据
     * @param param0
     */
    async loadEquipTypes({ commit, state }) {
      if (state.equipTypesLoaded) {
        return state.equipTypes;
      }

      try {
        const { callApi } = await import("@/tool/server");
        const result = await callApi("open/QueryEquipListTree", {});
        if (result && result.list) {
          commit("setEquipTypes", result.list);
          return result.list;
        }
        return [];
      } catch (error) {
        console.error("加载装备类型数据失败:", error);
        return [];
      }
    },
  },
  modules: {},
});
